#include "playpcmthread.h"
#include <SDL2/SDL.h>
#include <QFile>
//#define FREQ 44100
#define FREQ 44100

#define FORMAT AUDIO_F32LSB

#define SMAPLE_SIZE  SDL_AUDIO_BITSIZE(FORMAT)

#define CHANNELS 2

#define BYTE_PER_SAMPLE ((SMAPLE_SIZE * CHANNELS) >> 3)

#define SAMPLES 1024

#define BUFFER_SIZE (BYTE_PER_SAMPLE * SAMPLES)

#define AUDIO_PATH "/Users/tgy/Documents/ffmpeg/audio/recode_pcm_01.pcm"


struct ReadData{

    Uint8* data;
    int len;
    int pullLen;
};

PlayPCMThread::PlayPCMThread(QObject *parent) : QThread(parent)
{

    this->init();
}

PlayPCMThread::~PlayPCMThread()
{

    disconnect();

    requestInterruption();

    quit();

    wait();

    qDebug() << "PlayPCMThread destroy";

}

void PlayPCMThread::init()
{

   connect(this,&QThread::finished,this,&QThread::deleteLater);
}


void pullAudioCallback(void *userdata, Uint8 * stream,
                                    int len){

    memset(stream,0,len);

    ReadData* data = (ReadData *)userdata;

    if(data->len == 0) {

        return;
    }

    data->pullLen = data->len > len ? len:data->len;

    SDL_MixAudio(stream,data->data,data->pullLen,SDL_MIX_MAXVOLUME);

    data->data += data->pullLen;
    data->len -= data->pullLen;
}

void PlayPCMThread::run()
{

    if(SDL_Init(SDL_INIT_AUDIO)) {

        qDebug() << "audio init fail";
        return;
    }

    ReadData readData;
    SDL_AudioSpec spec;

    spec.freq = FREQ;
    spec.channels = CHANNELS;
    spec.format = FORMAT;
    spec.samples = SAMPLES;
    spec.callback = pullAudioCallback;
    spec.userdata = (void *)&readData;


    if(SDL_OpenAudio(&spec,nullptr)){

        SDL_Quit();
        qDebug() << "open audio fail";
        return;
    }

    QFile file(AUDIO_PATH);


    if(!file.open(QFile::ReadOnly)) {


        qDebug() << "open file " << AUDIO_PATH << "fail";
        SDL_CloseAudio();
        SDL_Quit();
        return;
    }


    SDL_PauseAudio(0);


    char buffer[BUFFER_SIZE];

    while (!isInterruptionRequested()) {

        if(readData.len > 0) {

            continue;
        }

        int len = file.read(buffer,BUFFER_SIZE);

        if(len <= 0) {

            int delay = (readData.pullLen / (BYTE_PER_SAMPLE * FREQ)) * 1000;
            qDebug() << "delay:" << delay;
            SDL_Delay(delay);
            break;
        }

        readData.data = (Uint8* )buffer;
        readData.len = len;
    }


    file.close();
    SDL_CloseAudio();
    SDL_Quit();

}
